package JianZhiOffer;

/**
 * 正则匹配
 * */
class Solution19 {


    /**
     * d[i][j] = if(p[j] == '.') d[i-1][j-1]
     *           if(p[j] == 'a') s[i] = p[j] && d[i-1][j-1]
     *           if(p[j-1:j] == '.*') d[i][j-2] || d[i-1][j]                                 不匹配.* || 匹配.*
     *           if(p[j-1:j] == 'a*') d[i][j-2] || (d[i-1][j] && s[i] == p[j-1])             不匹配a* || (匹配a* && s[i] == a)
     *
     * */
    public static boolean isMatch(String A, String B) {
        int n = A.length();
        int m = B.length();
        boolean[][] f = new boolean[n + 1][m + 1]; // i = 0代表A为空，j=0代表B为空,故长度都+1

        // 以下没有赋值都代表false

        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                //分成空正则和非空正则两种
                if (j == 0) {
                    // 空正则，则看A字符串是否为空，不为空则是false
                    f[i][j] = i == 0;
                } else {
                    // 是否是*
                    if (B.charAt(j - 1) != '*') {
                        // 不是*  则判断s[i] == p[j] 或者 p[j] == .
                        if (i > 0 && (A.charAt(i - 1) == B.charAt(j - 1) || B.charAt(j - 1) == '.')) {
                            f[i][j] = f[i - 1][j - 1];
                        }
                    } else {
                        //碰到 * 了，分为看和不看两种情况
                        //不看 则把p去掉后两位
                        if (j >= 2) {
                            f[i][j] |= f[i][j - 2];
                        }
                        //看 则判断s[i] == p[j-1] || p[j-1] == .
                        if (i >= 1 && j >= 2 && (A.charAt(i - 1) == B.charAt(j - 2) || B.charAt(j - 2) == '.')) {
                            f[i][j] |= f[i - 1][j];
                        }
                    }
                }
            }
        }
        return f[n][m];
    }

    public static void main(String[] args) {
        System.out.println(isMatch("abcdefgh", "abc.*fgh"));
    }

}
